<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Member_model extends CI_Model{
	var $CI;

	private $sesskey='member';
	private $tablefunc='member';
	private $sess=array();
	private $user;
	private $group;
	private $geted=FALSE;

	/**
	 * 登录错误
	 * 301 :帐号错误
	 * 302 :密码错误
	 * 303 :未审核
	 * 304 :已禁用
	 * 注册错误
	 * 401 :用户名必须填写
	 * 402 :用户名非法
	 * 403 :用户名已存在
	 * 411 :密码必须填写
	 * 412 :密码不符合要求(6个字符以上)
	 * 421 :邮箱必须填写
	 * 422 :邮箱格式不正确
	 * 423 :邮箱已注册过
	 * 431 :手机必须填写
	 * 432 :手机格式不正确
	 * 433 :手机号码已使用
	 * 443 :会员呢称重复
	 * 451 :会员组不存在
	 * 修改资料错误(部分与注册相同)
	 * 413 :必须输入旧密码
	 * 414 :密码不正确
	 */
	public $error;


	function __construct($table=''){
  		parent::__construct();
  		$this->CI =& get_instance();

  		$this->sess=$this->CI->session->userdata($this->sesskey);
	}

	public function getMessage($code=NULL){
		$messages=array(
			301 =>"帐号错误",
		 	302 =>"密码错误",
		 	303 =>"未审核",
		 	304 =>"已禁用",
		 	401 =>"用户名必须填写",
		 	402 =>"用户名非法",
		 	403 =>"用户名已存在",
		 	411 =>"密码必须填写",
		 	412 =>"密码不符合要求(6个字符以上)",
		 	413 =>"请输入当前密码",
		 	421 =>"邮箱必须填写",
		 	422 =>"邮箱格式不正确",
		 	423 =>"邮箱已注册过",
		 	431 =>"手机必须填写",
		 	432 =>"手机格式不正确",
		 	433 =>"手机号码已使用",
		 	443 =>"会员呢称重复",
		 	451 =>"会员组不存在",
			);
		if(is_null($code)){
			$code=$this->error;
		}
		if(isset($messages[$code])){
			return $messages[$code];
		}else{
			return '未知错误！';
		}
	}

	public function __get($key){
		//session中存在资料，直接返回
		if(isset($this->sess[$key])){
			return $this->sess[$key];
		}else{
			//有session,没有初始化用户资料，则自动初始化用户资料
			if(empty($this->user) && !$this->geted && !empty($this->sess)){
				$this->_getData();
			}
			if(!empty($this->user) && isset($this->user[$key])){
				return $this->user[$key];
			}else{
				return NULL;	//parent::__get($key);
			}
		}
	}

	function isLogin(){
		return !empty($this->sess) && !empty($this->sess['mid']);
	}
	
	function login($username,$userpass){
		
		//邮箱登录
		if(strpos($username, '@')){
			$where=array('email'=>$username);
		}elseif(preg_match('/^((\(\d{2,3}\))|(\d{3}\-))?1(3|5|8|9)\d{9}$/', $username)){
			$where=array('phone'=>$username);
		}else{
			$where=array('mname'=>$username);
		}

		$this->CI->Data_model->setTable($this->tablefunc);
		$member = $this->CI->Data_model->getSingle($where);
		if(empty($member)){
			$this->error=301;
			return false;
		}
		//暂时不限制审核
		/*if(isset($member['ischeck']) && $member['ischeck']==0){
			$this->error=303;
			return false;
		}*/
		if(isset($member['isdisable']) && $member['isdisable']==1){
			$this->error=304;
			return false;
		}
		if($member['mpwd']==md5pass($userpass,$member['mrnd'])){
			$this->CI->Data_model->editData(
				array('mid'=>$member['mid']),
				array(
					'logincount'=>$member['logincount']+1,
					'lasttime'=>time(),
					'lastip'=>$this->CI->input->ip_address()
					)
				);
			$this->setLogin($member);
			return true;
		}else{
			$this->error=302;
			return false;
		}
	}

	/**
	 * 注册用户
	 * 传入参数:
	 * $data:
	 * 返回代码:
	 */
	function register($data){
		//仅允许提交下列字段
		$data=array_intersect_key($data, array(
			'mname'=>'',
			'mpwd'=>'',
			'email'=>'',
			'phone'=>'',
			'sex'=>'',
			'mnick'=>'',
			'mgroup'=>'',
			));

		/**
		 * 检查资料
		 */
		if(empty($data['mname'])){
			$this->error=401;
			return false;
		}
		//用户名必须是5位以上，以字母开头，只能包含字母及数字
		if(!preg_match('/^\w[\w\d]{4,}$/', $data['mname'])){
			$this->error=402;
			return false;
		}

		if(empty($data['mpwd'])){
			$this->error=411;
			return false;
		}
		//用户密码必须是6位及以上,任意字符
		if(!preg_match('/^[\w\W]{6,}$/', $data['mpwd'])){
			$this->error=412;
			return false;
		}

		if(empty($data['email'])){
			$this->error=421;
			return false;
		}
		//邮箱格式
		if(!preg_match('/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/', $data['email'])){
			$this->error=422;
			return false;
		}

		/*if(empty($data['phone'])){
			$this->error=431;
			return false;
		}*/
		//手机号码格式
		if(!empty($data['phone']) && !preg_match('/^((\(\d{2,3}\))|(\d{3}\-))?1(3|5|8|9)\d{9}$/', $data['phone'])){
			$this->error=432;
			return false;
		}

		//会员组设置
		$this->CI->Data_model->setTable('membergroup');
		if(!empty($data['mgroup'])){
			$this->group=$this->CI->Data_model->getSingle(array('id'=>(int)$data['mgroup'],'allowreg'=>1));
			if(empty($this->group)){
				$this->error=451;
				return false;
			}
		}else{
			//获取默认组
			$this->group=$this->CI->Data_model->getSingle(array('isdefault'=>1),'','listorder ASC');
			//没有设定默认组则取第一个
			if(empty($this->group)){
				$this->group=$this->CI->Data_model->getSingle(array('allowreg'=>1),'','listorder ASC');
			}
			//没有会员组
			if(empty($this->group)){
				$this->group=array(
					'id'=>0,
					'groupname'=>'未分组',
					'needcheck'=>1
					);
			}
			$data['mgroup']=$this->group['id'];
		}
		if($this->group['needcheck']){
			$data['ischeck']=0;
		}


		if($this->checkUnique('mname',$data['mname'])){
			$this->error=403;
			return false;
		}
		if($this->checkUnique('email',$data['email'])){
			$this->error=423;
			return false;
		}
		/*if($this->checkUnique('phone',$data['phone'])){
			$this->error=433;
			return false;
		}*/

		if(empty($data['mnick'])){
			unset($data['mnick']);
		}else{
			if($this->checkUnique('mnick',$data['mnick'])){
				$this->error=443;
				return false;
			}
		}

		//非常用邮箱，验证真实性
		//..

		/**
		 * 验证通过
		 */
		//生成密码随机码
		$data['mrnd']=random_string('alnum',6);

		//生成密码
		$data['mpwd']=md5pass($data['mpwd'],$data['mrnd']);

		//填写标志数据
		$data['regip']=$this->CI->input->ip_address();
		$data['regdate']=time();

		//性别数据
		if(isset($data['sex'])){
			if(!in_array($data['sex'], array(0,1,2))){
				$data['sex']=0;
			}
		}

		//插入数据
		$mid=$this->CI->Data_model->addData($data,$this->tablefunc);

		//$mid=$this->Data_model->db->insert_id();

		//发送邮件
		//...

		//其它工作
		return $mid;
	}

	/**
	 * 保存用户资料
	 */
	function save($data){
		//仅允许提交下列字段
		$data=array_intersect_key($data, array(
			'mpwd'=>'',
			'oldmpwd'=>'',
			'email'=>'',
			'phone'=>'',
			'sex'=>'',
			'mnick'=>'',
			'avatar'=>''
			));
		/**
		 * 验证，必须输入旧密码才可以修改资料
		 */
		/*if(empty($data['oldmpwd'])){
			$this->error=413;
			return false;
		}

		if(md5pass($data['oldmpwd'],$this->mrnd) != $this->mpwd){
			$this->error=414;
			return false;
		}*/

		/**
		 * 检查资料
		 */
		if(isset($data['mpwd'])&&$data['mpwd']!=''){
			//用户密码必须是6位及以上,任意字符
			if(!preg_match('/^[\w\W]{6,}$/', $data['mpwd'])){
				$this->error=412;
				return false;
			}
		}

		if(!empty($data['email'])){
		
			/*if(empty($data['email'])){
				$this->error=421;
				return false;
			}*/
			//邮箱格式
			if(!preg_match('/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/', $data['email'])){
				$this->error=422;
				return false;
			}
			if($this->checkUnique('email',$data['email'],$this->mid)){
				$this->error=423;
				return false;
			}
		}else{
			unset($data['email']);
		}

		if(!empty($data['phone'])){
			/*if(empty($data['phone'])){
				$this->error=431;
				return false;
			}*/
			//手机号码格式
			if(!preg_match('/^((\(\d{2,3}\))|(\d{3}\-))?1(3|5|8|9)\d{9}$/', $data['phone'])){
				$this->error=432;
				return false;
			}
			if($this->checkUnique('phone',$data['phone'],$this->mid)){
				$this->error=433;
				return false;
			}
		}else{
			unset($data['phone']);
		}

		
		

		if(empty($data['mnick'])){
			$data['mnick']=$data['mname'];
		}else{
			if($this->checkUnique('mnick',$data['mnick'],$this->mid)){
				$this->error=443;
				return false;
			}
		}

		//非常用邮箱，验证真实性
		//..

		/**
		 * 验证通过
		 */
		if(isset($data['mpwd'])){
			//生成密码随机码
			$data['mrnd']=random_string('alnum',6);

			//生成密码
			$data['mpwd']=md5pass($data['mpwd'],$data['mrnd']);
		}

		//性别数据
		if(isset($data['sex'])){
			if(!in_array($data['sex'], array(0,1,2))){
				$data['sex']=0;
			}
		}

		//更新数据
		$this->CI->Data_model->editData(array('mid'=>$this->mid),$data,$this->tablefunc);

		//发送邮件
		//...

		//其它工作

		return true;
	}

	/**
	 * 检查用户资料是否重复
	 * $key 	要检查的键名
	 * $val 	要检查的值
	 * $id 		要排除的用户ID
	 * 返回值	TRUE 说明已存在
	 */
	function checkUnique($key, $val, $id=NULL){
		//仅提供下列字段的检查
		if(in_array($key, array('mname','email','phone','mnick'))){
			$this->CI->Data_model->setTable($this->tablefunc);
			$where=array($key=>$val);
			if(!is_null($id)){
				$where['mid !=']=(int)$id;
			}
			$data = $this->CI->Data_model->getSingle($where);
			return !empty($data);
		}
	}

	/**
	 * 初始化用户资料
	 */
	private function _getData(){
		$this->geted=true;
		if(!empty($this->sess) && isset($this->sess['mid'])){
			//$this->CI->Data_model->setTable($this->tablefunc);
			$db= &$this->CI->Data_model->db;
			$db->from($this->tablefunc.' m')
				->join('member_data md','m.mid=md.mid','left')
				->order_by('md.isdefault DESC,md.uptime DESC')
				->where(array('m.mid'=>$this->sess['mid']));
			$this->user=$db->get()->row_array();
		}
	}
	
	function setLogin($user){
		$this->CI->Data_model->setTable('membergroup');
		$this->group = $this->CI->Data_model->getSingle(array('id'=>$user['mgroup']));
		if(empty($this->group)){
			$this->group=array(
				'id'=>0,
				'groupname'=>'未分组'
				);
		}
		

		
		$this->sess = array(  //写入seessiom
				'mid' => $user['mid'],
				'mgroup' => $user['mgroup'],
				'groupname' => $this->group['groupname'],
				'mname' => $user['mname'],
				'mnick' => $user['mnick'],
				'isdetail' => $user['isdetail'],
				'city' => $user['city'],
				'age' => $user['age'],
				'sex' => $user['sex'],
				'email' => $user['email'],
				'profession' => $user['profession'],
				'honor' => $user['honor'],
				'story' => $user['story'],
		);
		
		/*$where=array('id'=>$user['mid']);            //个人简历
		$info = $this->CI->Data_model->getSingle($where,'member_info');
		if(count($info)>0 && $info!=''){
		
			$this->sess = array(  //写入seessiom
				'city' => $info['city'],
				'age' => $info['age'],
				'sex' => $info['sex'],
				'contact' => $info['contact'],
				'profession' => $info['profession'],
				'honor' => $info['honor'],
				'story' => $info['story'],
		);
		}*/
		
	
		$this->CI->session->set_userdata($this->sesskey,$this->sess);
	}
	
	function logout(){
		$this->sess=array();
		$userdata = array(
				'mid' => '',
				'mgroup' => '',
				'groupname' => '',
				'mname' => '',
				'mnick' => '',
		);
		$this->CI->session->unset_userdata($this->sesskey,$userdata);
	}
	
	
}